import React, { useState } from "react";
import { Card, Tabs, Form, Input, Button, Avatar, Upload, message } from "antd";
import { UserOutlined, UploadOutlined } from "@ant-design/icons";
import { useUser } from "../../contexts/UserContext";
import styled from "styled-components";

const { TabPane } = Tabs;

const ProfileContainer = styled.div`
  max-width: 800px;
  margin: 0 auto;
  padding: 24px;
`;

const AvatarContainer = styled.div`
  text-align: center;
  margin-bottom: 24px;
`;

const UserProfile: React.FC = () => {
  const { user, setUser } = useUser();
  const [loading, setLoading] = useState(false);

  const handleBasicInfoSubmit = async (values: any) => {
    try {
      setLoading(true);
      // TODO: 调用更新用户信息的API
      message.success("个人信息更新成功");
    } catch (error) {
      message.error("更新失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordSubmit = async (values: any) => {
    try {
      setLoading(true);
      // TODO: 调用修改密码的API
      message.success("密码修改成功");
    } catch (error) {
      message.error("修改失败，请重试");
    } finally {
      setLoading(false);
    }
  };

  const handleAvatarUpload = async (file: File) => {
    try {
      setLoading(true);
      // 创建 FormData
      const formData = new FormData();
      formData.append("avatar", file);

      // TODO: 调用上传头像API
      // const response = await fetch('/api/user/avatar', {
      //   method: 'POST',
      //   body: formData,
      // });

      // 模拟上传成功
      const avatarUrl = URL.createObjectURL(file);
      setUser({
        ...user!,
        avatar: avatarUrl,
      });

      message.success("头像上传成功");
    } catch (error) {
      message.error("头像上传失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <ProfileContainer>
      <Card>
        <AvatarContainer>
          <Upload
            name="avatar"
            showUploadList={false}
            beforeUpload={async (file) => {
              const isJpgOrPng =
                file.type === "image/jpeg" || file.type === "image/png";
              if (!isJpgOrPng) {
                message.error("只能上传 JPG/PNG 格式的图片！");
                return false;
              }
              const isLt2M = file.size / 1024 / 1024 < 2;
              if (!isLt2M) {
                message.error("图片大小不能超过 2MB！");
                return false;
              }
              await handleAvatarUpload(file);
              return false;
            }}
          >
            <div style={{ position: "relative", display: "inline-block" }}>
              <Avatar
                size={100}
                icon={<UserOutlined />}
                src={user?.avatar}
                style={{ cursor: "pointer" }}
              />
              <div
                style={{
                  position: "absolute",
                  bottom: 0,
                  right: 0,
                  background: "#fff",
                  borderRadius: "50%",
                  padding: 4,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.15)",
                }}
              >
                <UploadOutlined />
              </div>
            </div>
          </Upload>
        </AvatarContainer>

        <Tabs defaultActiveKey="basic">
          <TabPane tab="基本信息" key="basic">
            <Form
              layout="vertical"
              initialValues={{
                name: user?.name,
                email: user?.email,
                phone: user?.phone,
              }}
              onFinish={handleBasicInfoSubmit}
            >
              <Form.Item
                label="姓名"
                name="name"
                rules={[{ required: true, message: "请输入姓名" }]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="邮箱"
                name="email"
                rules={[
                  { required: true, message: "请输入邮箱" },
                  { type: "email", message: "请输入有效的邮箱地址" },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item
                label="手机号"
                name="phone"
                rules={[
                  { required: true, message: "请输入手机号" },
                  { pattern: /^1\d{10}$/, message: "请输入有效的手机号" },
                ]}
              >
                <Input />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存修改
                </Button>
              </Form.Item>
            </Form>
          </TabPane>

          <TabPane tab="修改密码" key="password">
            <Form layout="vertical" onFinish={handlePasswordSubmit}>
              <Form.Item
                label="当前密码"
                name="currentPassword"
                rules={[{ required: true, message: "请输入当前密码" }]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item
                label="新密码"
                name="newPassword"
                rules={[
                  { required: true, message: "请输入新密码" },
                  { min: 6, message: "密码长度不能小于6位" },
                ]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item
                label="确认新密码"
                name="confirmPassword"
                dependencies={["newPassword"]}
                rules={[
                  { required: true, message: "请确认新密码" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (!value || getFieldValue("newPassword") === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error("两次输入的密码不一致"));
                    },
                  }),
                ]}
              >
                <Input.Password />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" loading={loading}>
                  修改密码
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
    </ProfileContainer>
  );
};

export default UserProfile;
